package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.admin.dtos.AdminChannelPageDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsChannelDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private CacheService cacheService;
    /**
     * 管理端文章频道添加查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult AdminPageList(AdminChannelPageDto dto) {
        //1、参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.1、校验分页参数
        dto.checkParam();
        //2、分页条件查询
        //2.1、设置分页参数
        IPage iPage = new Page(dto.getPage(), dto.getSize());
        // 设置条件
        LambdaQueryWrapper<WmChannel> lqw = new LambdaQueryWrapper<>();
        //2.2、频道名称模糊查询
        lqw.like(dto.getName() != null, WmChannel::getName, dto.getName());
        //2.3、创建时间倒序
        lqw.orderByDesc(WmChannel::getCreatedTime);
        //2.4、状态精确查询
        lqw.eq(dto.getStatus() != null, WmChannel::getStatus, dto.getStatus());
        //2.3、查询
        page(iPage, lqw);
        //3、封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) iPage.getTotal());
        //3.1、完善参数
        pageResponseResult.setData(iPage.getRecords());
        pageResponseResult.setCode(AppHttpCodeEnum.SUCCESS.getCode());
        //4、返回响应结果
        return pageResponseResult;
    }

    /**
     * 新增文章频道
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmNewsChannelDto dto) {
        //1、参数校验
        if (dto == null || StringUtils.isEmpty(dto.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、保存
        //2.0、判断频道名称不能重复 通过名称搜索频道对象
        if (channelNameIsExit(dto))
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, dto.getName() + "已存在");
        //2.1、属性拷贝
        WmChannel wmChannel = new WmChannel();
        BeanUtils.copyProperties(dto, wmChannel);
        //2.2、前端没带过来的属性，手动赋值 todo status为空咋办
        wmChannel.setCreatedTime(new Date());
        wmChannel.setIsDefault(true);
        save(wmChannel);
        //3、删除redis数据
        cacheService.delete("channel_true");
        //4、返回响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 判断频道名称是否重复
     *
     * @param dto
     * @return
     */
    private boolean channelNameIsExit(WmNewsChannelDto dto) {
        WmChannel one = getOne(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, dto.getName()));
        //返回错误信息
        return one != null;
    }

    /**
     * 修改文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmNewsChannelDto dto) {
        //1、参数校验
        if (dto == null || dto.getStatus() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、判断频道是否被引用（查询wmNews表），被引用不能禁用
        List<WmNews> list1 = wmNewsService.list(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getChannelId, dto.getId()));
        //该频道下有文章
        if (list1 != null && list1.size() > 1) {
            //不能禁用
            if (!dto.getStatus()) {
                return ResponseResult.errorResult(AppHttpCodeEnum.CAN_NOT_FORBIDDEN);
            }
        }
        //3、修改文章频道状态
        update(Wrappers.<WmChannel>lambdaUpdate().eq(WmChannel::getId, dto.getId()).set(WmChannel::getStatus, dto.getStatus()));
        //4、修改频道其他信息
        //4.1、其他信息
        update(Wrappers.<WmChannel>lambdaUpdate().eq(WmChannel::getId, dto.getId())
                .set(WmChannel::getName, dto.getName())
                .set(dto.getDescription() != null, WmChannel::getDescription, dto.getDescription())//防止它只修改状态
                .set(dto.getOrd() != null, WmChannel::getOrd, dto.getOrd()));//防止它只修改状态
        //4.2、通过名字查询集合，如果两个，返回错误信息，就一个的话就可以 todo 事务未提交
        List<WmChannel> list = list(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getName, dto.getName()));
        if (list != null && list.size() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, dto.getName() + "已存在");
        }
        //5、频道修改后，清楚redis里面的数据
        cacheService.delete("channel_true");
        //6、返回响应结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        //1、参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2、 业务处理
        //2.1、启动的频道不能删除
        WmChannel wmChannel = getById(id);
        if (wmChannel.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CAN_NOT_DEL,"启用的频道不能删除");
        }
        //3、删除
        removeById(id);
        //4、频道删除后，清楚redis里面的数据
        cacheService.delete("channel_true");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询全部频道（启用状态）
     *
     * @return
     */
    @Override
    public ResponseResult findAll() {
        //1、先从redis查询
        String channelJson = cacheService.get("channel_true");
        if (StringUtils.isBlank(channelJson)) {
            //2、redis 没查到
            //2.1、数据库查询状态为启用状态的
            List<WmChannel> wmChannels = list(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getStatus, true));
            //2.2、放入redis
            cacheService.set("channel_true",JSON.toJSONString(wmChannels));
        }
        //3、再从redis里拿
        //转成原来list集合
        List<WmChannel> list = JSON.parseObject(channelJson, List.class);
        //返回响应结果
        return ResponseResult.okResult(list);
    }
}
